package io.zhiller.ollamaclient.api

import kotlinx.serialization.Serializable
import kotlinx.serialization.json.Json
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response
import java.io.IOException

enum class HttpStatus {
  SUCCESS, FAILURE, ERROR
}

@Serializable
data class HttpResponse<T>(val status: HttpStatus, val data: T?, val error: String? = null)

object HttpClient {
  val client = OkHttpClient()
  
  inline fun <reified T> getJsonFromUrl(url: String): HttpResponse<T> {
    val json = Json { ignoreUnknownKeys = true }
    return try {
      val request = Request.Builder().url(url).build()
      val response: Response = client.newCall(request).execute()
      if (response.isSuccessful) {
        val responseBody = response.body?.string()
        if (!responseBody.isNullOrEmpty()) {
          // 解析 JSON 数据
          val data = json.decodeFromString<T>(responseBody)
          HttpResponse(HttpStatus.SUCCESS, data)
        } else {
          HttpResponse(HttpStatus.FAILURE, null, "Empty response body")
        }
      } else {
        HttpResponse(
          HttpStatus.FAILURE, null, "Request failed: ${response.code} ${response.message}"
        )
      }
    } catch (e: IOException) {
      // 捕获网络异常
      HttpResponse(HttpStatus.ERROR, null, "Network error: ${e.message}")
    }
  }
  
  fun getPlainTextFromUrl(url: String): HttpResponse<String> {
    return try {
      val request = Request.Builder().url(url).build()
      val response: Response = client.newCall(request).execute()
      if (response.isSuccessful) {
        val responseBody = response.body?.string()
        if (!responseBody.isNullOrEmpty()) {
          // 解析 JSON 数据
          val data = responseBody
          HttpResponse(HttpStatus.SUCCESS, data)
        } else {
          HttpResponse(HttpStatus.FAILURE, null, "Empty response body")
        }
      } else {
        HttpResponse(
          HttpStatus.FAILURE, null, "Request failed: ${response.code} ${response.message}"
        )
      }
    } catch (e: IOException) {
      // 捕获网络异常
      HttpResponse(HttpStatus.ERROR, null, "Network error: ${e.message}")
    }
  }
}